//
//  ChatViewController.m
//  SportSocial
//
//  Created by yull on 15/1/3.
//  Copyright (c) 2015年 yull. All rights reserved.
//

#import "ChatViewController.h"
#import "ChatInputView.h"
#import "YPhotoView.h"
#import "UITableView+Util.h"

#import "PrivateMsgDao.h"
#import "CurrentChat.h"

#import "ChatTextCell.h"
#import "ChatAudioCell.h"
#import "ChatPicCell.h"

#import <AFHTTPRequestOperation.h>
#import "IMNet.h"

#import "PrivateMsgSender.h"
#import "GroupMsgSender.h"

#import "GroupDetailViewController.h"

#import "MUPAudio.h"

@interface ChatViewController () <UITableViewDataSource,UITableViewDelegate,ChatInputViewDelegate,UINavigationControllerDelegate,UIImagePickerControllerDelegate,ChatAudioCellDelegate,ChatPicCellDelegate>

@property (nonatomic, strong) ChatInputView *chatInputView;
@property (nonatomic, strong) YPhotoView *photoView;

@property (nonatomic, strong) UITableView *chatTableView;

@property (nonatomic, strong) NSMutableArray *chatArray;

@property (nonatomic, strong) UIActivityIndicatorView *indicatorView;

@property (nonatomic, assign) BOOL isLoading;

#pragma mark - 语音
@property (nonatomic, strong) ChatBaseMsg *playMessage;
@property (nonatomic, strong) AFHTTPRequestOperation *downloadAudioOperation;

@property (nonatomic, strong) MUPAudioPlayer *audioPlayer;

@end

@implementation ChatViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = RGB(245, 245, 245);
    
    [self initNavibar];
    
    [self initInputView];
    
    [self initChatTableView];
    
    [self initPhotoView];
    
    [self addNotification];
    
    [self loadMsgFromDB];
}

- (void)viewWillDisappear:(BOOL)animated
{
    if (self.playMessage) {
        self.playMessage.audioStatus = ChatMsgAudioStatusNone;
        [self.audioPlayer stop];
    }
    
    if (self.downloadAudioOperation) {
        [self.downloadAudioOperation cancel];
    }
    
    [super viewWillDisappear:animated];
}

- (void)initNavibar
{
    [self addCommonBackButton];
    
    self.navigationItem.title = self.msgSender.name;
    
    if ([self.msgSender isKindOfClass:[GroupMsgSender class]]) {
        UIButton *rightButton1 = [UIButton buttonWithType:UIButtonTypeCustom];
        rightButton1.frame = CGRectMake(0, 0, 40, 26);
        [rightButton1 setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [rightButton1 setTitle:@"资料" forState:UIControlStateNormal];
        [rightButton1 addTarget:self action:@selector(onClickDetail:) forControlEvents:UIControlEventTouchUpInside];
        UIBarButtonItem *rightItem1 = [[UIBarButtonItem alloc] initWithCustomView:rightButton1];
        self.navigationItem.rightBarButtonItem = rightItem1;
    }
}

- (void)initInputView
{
    self.chatInputView = [[ChatInputView alloc] initWithFrame:CGRectMake(0, self.view.height - ChatInputView_Height - Navibar_Height, self.view.width, ChatInputView_Height)];
    self.chatInputView.delegate = self;
    [self.view addSubview:self.chatInputView];

    [self.chatInputView addObserver:self forKeyPath:@"frame" options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld context:nil];
}

- (void)initPhotoView
{
    self.photoView = [[YPhotoView alloc] initWithFrame:self.view.bounds];
    [self.navigationController.view addSubview:self.photoView];
    
    self.photoView.hidden = YES;
}

- (void)initChatTableView
{
    CGRect rect = CGRectMake(0, 0, self.view.width, self.view.height  - self.chatInputView.height - Navibar_Height);
    
    self.chatTableView = [[UITableView alloc] initWithFrame:rect];
    self.chatTableView.delegate = self;
    self.chatTableView.dataSource = self;
    self.chatTableView.backgroundColor = [UIColor clearColor];
    self.chatTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.chatTableView.scrollsToTop = NO;
    [self.view addSubview:self.chatTableView];
}

- (void)initTableHeaderView
{
    UIView *tableHeaderView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 0, 40)];
    tableHeaderView.backgroundColor = [UIColor clearColor];
    self.indicatorView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
    self.indicatorView.frame = CGRectMake(0, 0, 20, 20);
    self.indicatorView.centerX = self.view.width / 2;
    self.indicatorView.centerY = 20;
    self.indicatorView.hidesWhenStopped = YES;
    [tableHeaderView addSubview:self.indicatorView];
    
    self.chatTableView.tableHeaderView = tableHeaderView;
    
    self.chatTableView.contentOffset = CGPointMake(0, 40);
}

- (void)removeTableHeader
{
    [self.chatTableView removeTableHeaderViewWithoutScroll];
}

- (void)addNotification
{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(addNewChatMsg:) name:@"AddNewPrivateChatMsg" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateSendStatus:) name:@"UpdateChatMsgStatus" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(uploadPicPercent:) name:@"UploadChatPicPercent" object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onReceive_User_Is_Delete:) name:@"user_is_deleted" object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onReceive_Group_Is_Delete:) name:@"group_is_deleted" object:nil];
}

- (void)dealloc
{
    [CurrentChat shareInstance].chatUser  = nil;
    [CurrentChat shareInstance].chatGroup = nil;
    
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [self.chatInputView removeObserver:self forKeyPath:@"frame"];
}

#pragma mark - 调整界面
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
    CGFloat oldHeight = [[change objectForKey:@"old"] CGRectValue].size.height;
    CGFloat height = self.chatInputView.height;
    
    if (oldHeight != height) {
        if (self.chatInputView.animated) {
            [UIView animateWithDuration:0.25f animations:^{
                self.chatInputView.top = self.view.height - height;
                self.chatTableView.height = self.view.height - height;
            }];
        }else{
            self.chatInputView.top = self.view.height - height;
            self.chatTableView.height = self.view.height - height;
            
            self.chatInputView.animated = YES;
        }
        
        if (self.chatInputView.style != ChatInputViewStyleAudio) {
            [self.chatTableView scrollsToBottom:YES];
        }
    }
}

#pragma mark - UITableViewDataSource,UITableViewDelegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.chatArray.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    ChatBaseMsg *chatMsg = [self.chatArray objectAtIndex:indexPath.row];
    if (chatMsg.msgType == ChatMsgTypeText) {
        return [ChatTextCell calculateCellHeightWithText:chatMsg.decodeContent];
    }else if (chatMsg.msgType == ChatMsgTypeAudio) {
        return [ChatAudioCell calculateCellHeight];
    }else {
        return [ChatPicCell calculateImageCellHeight];
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    ChatBaseMsg *chatMsg = [self.chatArray objectAtIndex:indexPath.row];
    if (chatMsg.msgType == ChatMsgTypeText) {
        static NSString *textIdentifier = @"TextCell";
        ChatTextCell *textCell = [tableView dequeueReusableCellWithIdentifier:textIdentifier];
        if (!textCell) {
            textCell = [[ChatTextCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:textIdentifier];
            textCell.delegate = self;
        }
        
        [textCell drawCellWithChatMsg:[self.chatArray objectAtIndex:indexPath.row]];
        return textCell;
    }else if (chatMsg.msgType == ChatMsgTypeAudio) {
        static NSString *audioIdentifier = @"AudioCell";
        ChatAudioCell *audioCell = [tableView dequeueReusableCellWithIdentifier:audioIdentifier];
        if (!audioCell) {
            audioCell = [[ChatAudioCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:audioIdentifier];
            audioCell.delegate = self;
        }
        [audioCell drawCellWithChatMsg:[self.chatArray objectAtIndex:indexPath.row]];
        return audioCell;

    }else {
        static NSString *picIdentifier = @"PicCell";
        ChatPicCell *picCell = [tableView dequeueReusableCellWithIdentifier:picIdentifier];
        if (!picCell) {
            picCell = [[ChatPicCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:picIdentifier];
            picCell.delegate = self;
        }
        [picCell drawCellWithChatMsg:[self.chatArray objectAtIndex:indexPath.row]];
        return picCell;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (self.chatInputView.style != ChatInputViewStyleNormal) {
        self.chatInputView.style = ChatInputViewStyleNormal;
    }
}

#pragma mark - UIScrollViewDelegate
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    if(self.chatTableView.tableHeaderView && scrollView.contentOffset.y < 40 && !self.isLoading && self.chatArray) {
        self.isLoading = YES;
        [self.indicatorView startAnimating];
        
        [self performSelector:@selector(selectHistoryChatMsgFromDB) withObject:nil afterDelay:1.0f];
    }
    
    if (self.chatInputView.style != ChatInputViewStyleNormal && scrollView.dragging) {
        self.chatInputView.style = ChatInputViewStyleNormal;
    }
}

#pragma mark - ChatInputViewDelegate
- (void)sendText:(NSString *)text
{
    [self.msgSender createMsgWithText:text];
}

- (void)recordAudioUrl:(NSString *)url audioData:(NSData *)audioData audioLength:(NSInteger)audioLength
{
    [self.msgSender createMsgWithAudioData:audioData audioLength:audioLength path:url];
}

- (void)beginRecord
{
    if (self.audioPlayer.isPlaying) {
        [self onAudioCellTapWithChatMsg:self.playMessage];
    }
}

- (void)selectImageFromAlbum
{
    NSUInteger sourceType = 0;//初始化调用相机相册的方法
    sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;//调用相机
    
    UIImagePickerController * imagePickerController = [[UIImagePickerController alloc] init];
    imagePickerController.delegate = self;
    imagePickerController.sourceType = sourceType;
    [self presentViewController:imagePickerController animated:YES completion:nil];
}

- (void)takePhoto
{
    NSUInteger sourceType = 0;//初始化调用相机相册的方法
    sourceType = UIImagePickerControllerSourceTypeCamera;//调用相册
    
    UIImagePickerController * imagePickerController = [[UIImagePickerController alloc] init];
    imagePickerController.delegate = self;
    imagePickerController.sourceType = sourceType;
    [self presentViewController:imagePickerController animated:YES completion:nil];
}

#pragma mark - UIImagePickerControllerDelegate
//点击use调用的方法
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    //要上传的图片
    UIImage * image = [info objectForKey:UIImagePickerControllerOriginalImage];
    [picker dismissViewControllerAnimated:YES completion:nil];
    
    [self.msgSender createMsgWithImage:image];
    
    if ([UIDevice currentDevice].systemVersion.floatValue >= 7.0f) {
        [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];
    }
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    [picker dismissViewControllerAnimated:YES completion:nil];
    
    if ([UIDevice currentDevice].systemVersion.floatValue >= 7.0f) {
        [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];
    }
}


#pragma mark - NSNotification
- (void)addNewChatMsg:(NSNotification *)notification
{
    NSArray *msgArray = notification.object;
    
    [self.chatArray addObjectsFromArray:msgArray];
    
    dispatch_async(dispatch_get_main_queue(), ^{
        [self.chatTableView reloadData];
        
        [self.chatTableView scrollsToBottom:YES];
    });
}

- (void)updateSendStatus:(NSNotification *)notification
{
    UInt64 dbId = [[notification.userInfo objectForKey:@"dbId"] longLongValue];
    ChatMsgSendStatus status = [[notification.userInfo objectForKey:@"status"] integerValue];
    
    for (ChatBaseMsg *chatMsg in self.chatArray) {
        if (chatMsg.dbId == dbId) {
            chatMsg.sendStatus = status;
            break;
        }
    }
}

- (void)uploadPicPercent:(NSNotification *)notification
{
    UInt64 msgId = [[notification.userInfo objectForKey:@"msgId"] longLongValue];
    NSInteger percent = [[notification.userInfo objectForKey:@"percent"] integerValue];
    
    for (ChatBaseMsg *msg in self.chatArray) {
        if (msg.dbId == msgId) {
            msg.picUploadPercent = percent;
        }
    }
}

- (void)onReceive_User_Is_Delete:(NSNotification *)notification
{
    NSDictionary *dic = notification.userInfo;
    
    UInt64 userId = [[dic objectForKey:@"userid"] longLongValue];
    
    if ([CurrentChat shareInstance].chatUser && [CurrentChat shareInstance].chatUser.userId == userId) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.navigationController popToRootViewControllerAnimated:YES];
        });
    }
}

- (void)onReceive_Group_Is_Delete:(NSNotification *)notification
{
    NSDictionary *dic = notification.userInfo;
    
    UInt64 groupId = [[dic objectForKey:@"groupid"] longLongValue];
    
    if ([CurrentChat shareInstance].chatGroup && [CurrentChat shareInstance].chatGroup.group_id == groupId) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.navigationController popToRootViewControllerAnimated:YES];
        });
    }
}

#pragma mark - 数据库
- (void)loadMsgFromDB
{
    if (!self.chatArray) {
        self.chatArray = [NSMutableArray array];
    }
    
    [self.chatArray addObjectsFromArray:[self.msgSender selectChatMsg]];
    
    if (self.chatArray.count >= 10) {
        [self initTableHeaderView];
    }
    
    if (self.chatArray.count > 0) {
        [self.chatTableView reloadData];
        
        [self.chatTableView scrollsToBottom:YES];
    }
}

- (void)selectHistoryChatMsgFromDB
{
    UInt64 beginId = [(ChatBaseMsg *)self.chatArray.firstObject dbId];
    NSArray *array = [self.msgSender selectHistoryMsgWithDbId:beginId];
    
    [self.chatArray insertObjects:array atIndexes:[NSIndexSet indexSetWithIndexesInRange:NSMakeRange(0, array.count)]];
    
    @weakify(self);
    dispatch_async(dispatch_get_main_queue(), ^{
        @strongify(self);
        if (array.count < 10) {
            [self removeTableHeader];
        }
        
        if (array.count > 0) {
            [self.chatTableView reloadDataWithoutScroll];
        }
        self.isLoading = NO;
        [self.indicatorView stopAnimating];
    });
}

#pragma mark - ChatBaseCellDelegate
- (void)onResend:(ChatBaseMsg *)message
{
    [self.msgSender resendMsg:message];
}

#pragma mark - 语音播放
- (void)onAudioCellTapWithChatMsg:(ChatBaseMsg *)chatMsg
{
    if (chatMsg.audioStatus == ChatMsgAudioStatusNone) {
        if (self.playMessage) {
            self.playMessage.audioStatus = ChatMsgAudioStatusNone;
            self.playMessage = nil;
            if (self.playMessage.audioStatus == ChatMsgAudioStatusLoading) {
                [self cancelDownLoadAudio];
            }else if (self.playMessage.audioStatus == ChatMsgAudioStatusPlaying) {
                [self.audioPlayer stop];
            }
        }
        
        self.playMessage = chatMsg;
        NSData *data = [self getAudioWithMessage:chatMsg];
        
        if (data.length > 0) {
            [self startPlayAudioWithData:data];
        }else {
            self.playMessage.audioStatus = ChatMsgAudioStatusLoading;
            
            [self downLoadAudioWithChatMsg:chatMsg];
        }
    }else if (chatMsg.audioStatus == ChatMsgAudioStatusLoading) {
        chatMsg.audioStatus = ChatMsgAudioStatusNone;
        self.playMessage = nil;
        [self cancelDownLoadAudio];
    }else if (chatMsg.audioStatus == ChatMsgAudioStatusPlaying) {
        chatMsg.audioStatus = ChatMsgAudioStatusNone;
        self.playMessage = nil;
        [self.audioPlayer stop];
    }
}

#pragma mark 开始播放
- (void)startPlayAudioWithData:(NSData *)data
{
    self.playMessage.audioStatus = ChatMsgAudioStatusPlaying;
    
    if (!self.audioPlayer) {
        self.audioPlayer = [MUPAudioPlayer sharedInstance];
    }
    [self.audioPlayer playAudioWithData:data error:nil];
    
    if (!self.playMessage.isRead) {
        self.playMessage.isRead = YES;
        if ([self.msgSender updateReadWithMsgId:self.playMessage.dbId]) {
            NSLog(@"更新已读状态成功!");
        }
    }

}

#pragma mark 检查音频是否存在
- (NSData *)getAudioWithMessage:(ChatBaseMsg *)chatMsg
{
    NSString *audioPath = chatMsg.localPath;
    NSData *data = [NSData dataWithContentsOfFile:audioPath];
    return data;
}

#pragma mark 下载语音
- (void)downLoadAudioWithChatMsg:(ChatBaseMsg *)chatMsg
{
    self.downloadAudioOperation = [IMNet  getAudioWithUrl:chatMsg.url successBlock:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSData *data = responseObject;

        NSString *audioUrl = [NSString stringWithFormat:@"%@/%@.wav",[FunctionMethod audioDiretoryPath],chatMsg.decodeContent];
        NSURL *wavUrl = [NSURL fileURLWithPath:audioUrl isDirectory:NO];
        
        NSURL *tempUrl = [NSURL fileURLWithPath:[[NSString alloc] initWithFormat:@"%@/%@.amr",NSTemporaryDirectory(),chatMsg.decodeContent] isDirectory:NO];
        [data writeToURL:tempUrl atomically:YES];
        [MUPAudioUtility convertAmrFile:tempUrl toWavFile:wavUrl error:nil];
        
        NSData *wavData = [NSData dataWithContentsOfURL:wavUrl];
        if (wavData) {
            [self startPlayAudioWithData:wavData];
        }
    } failBlock:^(AFHTTPRequestOperation *operation, NSError *error) {
        chatMsg.audioStatus = ChatMsgAudioStatusNone;
    }];
}

- (void)cancelDownLoadAudio
{
    if (self.downloadAudioOperation) {
        [self.downloadAudioOperation cancel];
    }
}

#pragma mark - ChatPicCellDelegate
- (void)picClickChatMsg:(ChatBaseMsg *)chatMsg image:(UIImage *)image
{
    NSArray *picArray = [self.msgSender selectAllPicMsg];
    NSArray *visibleCells = [self.chatTableView visibleCells];
    NSMutableArray *photoArray = [NSMutableArray array];
    NSInteger index = 0;
    
    for (NSInteger i = 0;i<picArray.count;i++) {
        ChatBaseMsg *tmpMsg = [picArray objectAtIndex:i];
        if (tmpMsg.dbId == chatMsg.dbId) {
            index = i;
        }
        
        YPhoto *photo = [[YPhoto alloc] init];

        if (tmpMsg.localPath) {
            UIImage *tmpImage = [UIImage imageWithContentsOfFile:tmpMsg.localPath];
            photo.thumbImage = tmpImage;
            photo.image = tmpImage;
        }else {
            if (image) {
                photo.thumbImage = image;
            }else{
                photo.thumbImage = [UIImage imageNamed:@"chat_img_default_white"];
            }
            photo.imageUrl = tmpMsg.bigImageUrl;
        }
        
        for (ChatBaseCell *cell in visibleCells) {
            if (![cell isKindOfClass:[ChatPicCell class]]) {
                continue;
            }else if (tmpMsg.dbId == cell.chatMsg.dbId) {
                ChatPicCell *picCell = (ChatPicCell *)cell;
                CGRect rect = [self.navigationController.view convertRect:picCell.chatImageView.frame fromView:picCell.chatContentView];
                photo.imageRect = rect;
            }
        }
        [photoArray addObject:photo];
    }
    self.photoView.photoArray = photoArray;
    
    self.photoView.showIndex = index;
    
    [self.photoView showPhotoViewWithImage:image];
    
    self.chatInputView.style = ChatInputViewStyleNormal;
}

#pragma mark - Action
- (void)onClickDetail:(id)sender
{
    UIViewController *detailViewController = [self.msgSender createDetailViewController];
    [self.navigationController pushViewController:detailViewController animated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

@end
